﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Security.Principal;
using System.DirectoryServices;
using System.Globalization;

namespace TFSAutoShelve
{
    /// <summary>
    /// A helper class for working with Active Directory.
    /// </summary>
    internal class ADHelper
    {
        /// GetCurrentUserEmailAddress
        /// <summary>
        /// Returns the e-mail address of the current user.
        /// </summary>
        /// <returns>The e-mail address</returns>
        internal static string GetUserEmailAddress()
        {
            const string PROPERTY_MAIL = "mail";

            // Get the username of the current user
            WindowsIdentity identity = WindowsIdentity.GetCurrent();
            if (identity.IsAnonymous) return null;
            string userName = identity.Name;

            // Remove the domain if present
            if (userName.IndexOf("\\", StringComparison.Ordinal) != -1)
            {
                userName = userName.Split('\\')[1];
            }

            // Get the root directory entry to search for the user in
            DirectoryEntry directoryRoot = new DirectoryEntry();

            // Build the search criteria
            string searchFilter = String.Format(
                CultureInfo.InvariantCulture,
                Properties.Resources.USER_DIRECTORY_SEARCH,
                userName);

            // Search for the user
            DirectorySearcher searcher = new DirectorySearcher(directoryRoot, searchFilter);
            SearchResult result = searcher.FindOne();

            // Verify the user was found
            if (result == null)
            {
                string sMsg = string.Format(CultureInfo.InvariantCulture, Properties.Resources.ERR_FAILED_TO_FIND_USER, userName);
                throw new System.ArgumentException(sMsg);
            }

            // Get the directory entry that corresponds to the user
            DirectoryEntry user = new DirectoryEntry(result.Path);

            return GetDirectoryEntryStringValue(user, PROPERTY_MAIL);

        } // end GetCurrentUserEmailAddress()

        /// GetDirectoryEntryStringValue
        /// <summary>
        /// Gets a single-valued string property value.
        /// </summary>
        /// <param name="entry">Entry</param>
        /// <param name="propertyName">The property name</param>
        /// <returns>The value, or String.Empty if not present</returns>
        internal static string GetDirectoryEntryStringValue(DirectoryEntry entry, string propertyName)
        {
            string s = string.Empty;

            // In AD, if the property has no value, the 
            //  directory object will not contain that property
            if (entry.Properties.Contains(propertyName))
            {
                s = (entry.Properties[propertyName][0]) as string;
            }

            return s;

        } // end GetStringValue()
    }
}
